package com.asen.commons.core.jdbc.util;

import com.asen.commons.core.jdbc.builder.SqlBuilder;
import com.asen.commons.core.jdbc.param.ParamObject;
import com.asen.commons.core.jdbc.param.ParamStatementSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 日志工具类
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-03
 */
public class LogUtils {

    private Logger logger;

    private LogUtils(Class<?> clazz) {
        this.logger = LoggerFactory.getLogger(clazz);
    }

    public static LogUtils getLogger(Class<?> clazz) {
        return new LogUtils(clazz);
    }

    public void log(SqlBuilder sqlBuilder) {
        logSql(sqlBuilder.getSql(), sqlBuilder.getParams());
    }

    public void logSql(String sql) {
        logSql(sql, null);
    }

    public void logSql(String sql, ParamStatementSetter params) {
        if (!logger.isDebugEnabled()) {
            return;
        }

        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        StringBuilder sb = new StringBuilder();
        sb.append(stackTrace[2].getMethodName());
        sb.append(" - ");
        sb.append("(");
        sb.append(stackTrace[2].getFileName());
        sb.append(":");
        sb.append(stackTrace[2].getLineNumber());
        sb.append(")");
        logger.debug(sb.toString());

        sb.setLength(0);
        sb.append("==>  Preparing: ").append(sql);
        logger.debug(sb.toString());

        sb.setLength(0);
        if (params != null && params.size() > 0) {
            sb.append("==> Parameters: ");
            for (int i = 0; i < params.size(); i++) {
                ParamObject param = params.getParam(i);
                if (i > 0) {
                    sb.append(", ");
                }
                sb.append(param.getValue())
                        .append(" (")
                        .append(param.getJavaType().getSimpleName())
                        .append(")");
            }
            logger.debug(sb.toString());
        }
    }

    public void logResult(int total, long begin, long end) {
        logResult(total, end - begin);
    }

    public void logResult(int total, long mills) {
        if (!logger.isDebugEnabled()) {
            return;
        }

        StringBuilder sb = new StringBuilder()
                .append("<==      Total: ")
                .append(total)
                .append(", ")
                .append(mills)
                .append("ms");
        logger.debug(sb.toString());
    }

    public void logResultUnknown(long begin, long end) {
        logResultUnknown(end - begin);
    }

    public void logResultUnknown(long mills) {
        if (!logger.isDebugEnabled()) {
            return;
        }

        logger.debug("<==      Total: unknown, " + mills + "ms");
    }

}
